package com.cc.blog.handler;

import com.alibaba.fastjson.JSON;
import com.cc.blog.entity.SysUser;
import com.cc.blog.service.LoginService;
import com.cc.blog.service.TokenService;
import com.cc.blog.utils.UserThreadLocal;
import com.cc.blog.vo.ErrorCode;
import com.cc.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.确认访问的是handler的方法（Controller的方法）
         * 2.判断token是否为空，如果为空，则为登录
         * 3.如果不为空，调用LoginService的checkToken方法
         * 4.认证成功则放行
         */
        if(!(handler instanceof HandlerMethod)){
            return true;//如果不是handler的方法直接放行，类似static的方法
        }
        String token = request.getHeader("Authorization");
        //记录日志
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.TOKEN_ERROR.getCode(), "未登录");
            //让浏览器识别是json
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.TOKEN_ERROR.getCode(), "未登录");
            //让浏览器识别是json
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        /**
         *   在controller层直接获取用户信息
         */
        UserThreadLocal.put(sysUser);
        return true;
    }

    /**
     * 删除ThreadLocal的信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
